package KylinComponents

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gormLogger "gorm.io/gorm/logger"
	"time"
)

var appMysqlDb *gorm.DB

func AppMysqlConnector() *gorm.DB {
	go LogInfo(nil, "Start Connect mysql server")

	cfg := InitConfigFromToml()
	host, _ := cfg.GetValue("APP_MYSQL", "host")
	port, _ := cfg.GetValue("APP_MYSQL", "port")
	username, _ := cfg.GetValue("APP_MYSQL", "username")
	password, _ := cfg.GetValue("APP_MYSQL", "password")
	database, _ := cfg.GetValue("APP_MYSQL", "database")

	dsn := username + ":" + password + "@tcp(" + host + ":" + port + ")/" + database + "?charset=utf8mb4&parseTime=True&loc=Local"

	appMysqlDb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		go LogError(nil, fmt.Sprintf("%s", err))
		return nil
	} else {
		go LogInfo(nil, "Mysql connection succeed!")
	}
	//设置连接最大超时时间
	sqlDB, _ := appMysqlDb.DB()
	//sqlDB.SetConnMaxIdleTime(time.Second * 10) todo not support
	sqlDB.SetConnMaxLifetime(time.Second * 10)
	appMysqlDb.Logger.LogMode(gormLogger.Info)
	go LogInfo(nil, "Return mysql connect")

	return appMysqlDb

}
